from flask import Blueprint, request, jsonify
from flask_login import login_required, current_user
from app.models import Role, db
from datetime import datetime

bp = Blueprint('roles', __name__)


@bp.route('/get_roles', methods=['GET', 'POST'])
@login_required
def get_roles():
    roles = Role.query.filter_by(user_id=current_user.id).order_by(Role.updated_at.desc()).all()
    print(roles)
    return jsonify({
        'roles': [{
            'id': role.id,
            'name': role.name,
            'description': role.description,
            'system_prompt': role.system_prompt,
            'created_at': role.created_at.isoformat(),
            'updated_at': role.updated_at.isoformat()
        } for role in roles]
    })


@bp.route('/create_role', methods=['POST'])
@login_required
def create_role():
    data = request.get_json()

    if not data or not data.get('name') or not data.get('system_prompt'):
        return jsonify({'error': '角色名称和系统提示是必填项'}), 400

    role = Role(
        user_id=current_user.id,
        name=data['name'],
        description=data.get('description', ''),
        system_prompt=data['system_prompt']
    )

    db.session.add(role)
    db.session.commit()

    return jsonify({
        'success': True,
        'role': {
            'id': role.id,
            'name': role.name,
            'description': role.description,
            'system_prompt': role.system_prompt
        }
    })


@bp.route('/update_role', methods=['PUT'])
@login_required
def update_role():
    data = request.get_json()
    role_id = data.get('id')

    if not role_id:
        return jsonify({'error': '缺少角色ID'}), 400

    role = Role.query.get(role_id)
    if not role or role.user_id != current_user.id:
        return jsonify({'error': '角色不存在或无权修改'}), 404

    if 'name' in data:
        role.name = data['name']
    if 'description' in data:
        role.description = data['description']
    if 'system_prompt' in data:
        role.system_prompt = data['system_prompt']

    role.updated_at = datetime.utcnow()
    db.session.commit()

    return jsonify({
        'success': True,
        'role': {
            'id': role.id,
            'name': role.name,
            'description': role.description,
            'system_prompt': role.system_prompt
        }
    })


@bp.route('/delete_role/<role_id>', methods=['DELETE'])
@login_required
def delete_role(role_id):
    print(role_id)
    role = Role.query.get(role_id)
    if not role or role.user_id != current_user.id:
        return jsonify({'error': '角色不存在或无权删除'}), 404

    db.session.delete(role)
    db.session.commit()

    return jsonify({'success': True})
